package com.px.user.mapper;

import com.px.user.entity.Reward;
import com.px.user.entity.RewardHis;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public interface RewardMapper {

    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    @Insert("insert into reward (name,avatar,animation,money,isFull) values (#{name},#{avatar},#{animation},#{money},#{isFull})")
    void insert(Reward reward);

    @Insert("update reward set name=ifnull(#{name},name),avatar=ifnull(#{avatar},avatar)," +
            "animation=ifnull(#{animation},animation),money=ifnull(#{money},money), isFull=ifnull(#{isFull},isFull) where id=#{id}")
    void update(Reward reward);

    @Select("select * from reward where id=#{id}")
    Reward findById(Long id);

    @Select("select * from reward order by money asc")
    List<Reward> findAll();

    @Delete("delete from reward where id=#{id}")
    void delete(Long id);

    /**
     * 打赏记录
     *
     * @param rewardHis
     */
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    @Insert("insert into reward_his (rewardId,roomId,fromUserId,money,toUserId) " +
            "values (#{rewardId},#{roomId},#{fromUserId},#{money},#{toUserId})")
    void insertRewardHis(RewardHis rewardHis);

    @Select({"<script>",
            "select reward_his.*,user1.nickname as fromNickname,user2.nickname as toNickname from reward_his",
            " left join user as user1 on reward_his.fromUserId=user1.id",
            " left join user as user2 on reward_his.toUserId=user2.id",
            "<where>",
            " <if test='fromUserId != null'>and reward_his.fromUserId = #{fromUserId}</if>",
            " <if test='qstart != null'>and reward_his.createTime >= #{qstart}</if>",
            " <if test='qend != null'>and reward_his.createTime <![CDATA[<=]]> #{qend}</if>",
            "</where>",
            "order by ${orderField} desc limit #{startIndex},#{limit}",
            "</script>"})
    List<RewardHis> paging(RewardHis rewardHis);

    @Select({"<script>",
            "select count(1) from reward_his",
            "<where>",
            "<if test='fromUserId != null'>and fromUserId = #{fromUserId}</if>",
            "<if test='qstart != null'>and createTime >= #{qstart}</if>",
            "<if test='qend != null'>and createTime <![CDATA[<=]]> #{qend}</if>",
            "</where>",
            "</script>"})
    Integer pagingCount(RewardHis rewardHis);
}
